package shiqi.model;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.ToString;
import org.apache.commons.lang3.StringUtils;

import java.lang.reflect.Field;

/**
 * @program: ascend
 * @description: 用户类
 * @author: shiqi
 * @create: 2022-03-17 16:15
 **/
@Data
@AllArgsConstructor
@NoArgsConstructor
@ToString
public class User {

    //用户id
    private Long userId;
    //用户名
    private String userName;
    //密码
    private String password;

    /**
     * @author shiqi
     * @createTime 2022/3/17 16:34
     * @desc 判断所有的参数是否相等，利用反射
     * @param
     * @return boolean
     */
    public boolean isSame(User user) throws IllegalAccessException {
        boolean result = true;
        Class<? extends User> userClass = this.getClass();
        // 获得所有声明的字段，即包括public、private和proteced，但是不包括父类的申明字段。
        Field[] declaredFields = userClass.getDeclaredFields();
        for (Field field: declaredFields) {
            Class<?> type = field.getType();
            if (type.equals(String.class)) {
                String source = (String)field.get(this);
                String target = (String)field.get(user);
                if (StringUtils.isBlank(source) && StringUtils.isBlank(target)) {
                    result = true;
                } else if (StringUtils.isBlank(source) || StringUtils.isBlank(target)) {
                    result = false;
                } else if (!source.equals(target)) {
                    result = false;
                }
            } else if (type.equals(Long.class)) {
                Long source = (Long)field.get(this);
                Long target = (Long)field.get(user);
                if (source == null && target == null) {
                    result = true;
                } else if (source == null || target == null) {
                    result = true;
                } else if (source.longValue() != target.longValue()) {
                    result = false;
                }
            }
        }
        return result;
    }
}
